package com.crm.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.crm.constans.Constants;
import com.crm.domain.dto.LoginDto;
import com.crm.domain.entity.User;
import com.crm.exception.BaseException;
import com.crm.mapper.UserMapper;
import com.crm.properties.JwtTokenManagerProperties;
import com.crm.service.LoginService;
import com.crm.utils.BasicEnum;
import com.crm.utils.JwtUtil;
import com.crm.utils.RedisCache;
import com.crm.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Xanny
 */
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {
    @Autowired
    private RedisCache redisCache;

    private final UserMapper userMapper;

    private final JwtTokenManagerProperties jwtTokenManagerProperties;

    @Override
    public String login(LoginDto loginDto) throws BaseException {
        //1.账号密码校验
        String username = loginDto.getUsername();
        if(username.length() > Constants.USERNAME_LENGTH){
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }
        String password = loginDto.getPassword();
        if(password.length() <6 && password.length()>12){
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }
        //2.验证码校验 //
        validateCaptcha(username, loginDto.getCode(), loginDto.getUuid());
        //3.完成登录的业务逻辑
        //3.1查询数据库中是否有用户信息
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUserName, username));

        //判断用户是否存在
        if(ObjectUtil.isEmpty(user)){
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }

        //判断用户是否被禁用
        if(user.getDelFlag().equals(Constants.FAIL)){
            throw new BaseException(BasicEnum.ACCOUNT_DISABLED);
        }
        //3.2判断该账号 密码是否正确 账号是否被删除
        if(user.getPassword().equals(password)){
            //登录成功返回token
            Map<String,Object> claims = new HashMap<>();
            claims.put("currentUser", JSONUtil.toJsonStr(user));

            String token = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), jwtTokenManagerProperties.getTtl(), claims);
            return token;
        }else {
            throw new BaseException(BasicEnum.PASSWORD_ERROR);
        }

    }


    @Override
    public void logout() {

    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    @Override
    public void validateCaptcha(String username, String code, String uuid)
    {
        String verifyKey = "captcha_codes:" + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        if (captcha == null)
        {
            throw new BaseException(BasicEnum.VALIDATION_FAILED);
        }
        redisCache.deleteObject(verifyKey);
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new BaseException(BasicEnum.VALIDATION_FAILED);
        }
    }
}

